package com.example.gallery;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.board.R;
import com.example.gallery.ImageListAdapter.onTestClick;



public class DetailActivity extends Activity implements OnClickListener, OnItemClickListener, OnItemLongClickListener, OnLongClickListener{
	static final String TAG = "DETAILACTIVITY";
//	private int TAKE_GALLERY = 2; // �ٹ��ÿ� ���� ���� �ڵ尪 ����

	BoardHandler boardDB;
	ImageHandler imageDB;
	ArrayList<ImageDTO> imageList;
	ImageListAdapter adapter;
	
	int no;
	int succ = 0;
	String file_path;
	
	ImageView iv;
	Button btn_delete;
	Button btn_update;
	ImageButton btn_camera;
	ImageButton btn_gallery;
	Button btn_delete_picture;
	TextView tv_selected_count;
	TextView tv_selected_images;
	
	TextView tv_no;
	TextView tv_id;
	EditText et_title;
	EditText et_content;
	ImageView mImageView;
	ListView lv_list;
	GridView grid_image;
	CheckBox checkBox;
	OnClickListener callback;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail);
		Log.i(TAG, "onCreate");
		
		lv_list = (ListView) findViewById(android.R.id.list);
		tv_no = (TextView) findViewById(R.id.tv_no);
		tv_id = (TextView) findViewById(R.id.tv_id);
		et_title = (EditText) findViewById(R.id.et_title);
		et_content = (EditText) findViewById(R.id.et_content);
//		iv = (ImageView) findViewById(R.id.iv);
		grid_image = (GridView) findViewById(R.id.grid_image);
		
		tv_selected_count = (TextView) findViewById(R.id.tv_selected_count);
		tv_selected_images = (TextView) findViewById(R.id.tv_selected_images);
		btn_camera = (ImageButton) findViewById(R.id.b_camera);
		btn_gallery = (ImageButton) findViewById(R.id.b_gallery);
		btn_delete_picture = (Button) findViewById(R.id.btn_delete_picture);
		
		btn_delete = (Button) findViewById(R.id.btn_delete);
		btn_update = (Button) findViewById(R.id.btn_update);
		
		btn_camera.setOnClickListener(this);
		btn_gallery.setOnClickListener(this);
		btn_delete_picture.setOnClickListener(this);
		btn_delete.setOnClickListener(this);
		btn_update.setOnClickListener(this);
		grid_image.setOnItemClickListener(this);
		grid_image.setOnLongClickListener(this);
		grid_image.setOnItemLongClickListener(this);
		
		
		/*
		GalleryAdapter adapter = new GalleryAdapter(this, R.layout.iv_row, imageList);
		
		adapter.notifyDataSetChanged();
		lv_list.invalidate();
		lv_list.setAdapter(adapter);
		lv_list.invalidate();
		adapter.notifyDataSetChanged();
		*/
		
	/*	ImageView  로 조회
//		ImageView[] iView = new ImageView[imageList.size()];
		String[] file_name = new String[imageList.size()];
		
		Log.i(TAG, "�����"+imageList.size()+"");
		for(int i=0; i<imageList.size(); i++){
			ImageView iv = new ImageView(DetailActivity.this);
			ImageDTO dto = new ImageDTO();
			dto.setNAME(imageList.get(i).getNAME());

			file_name[i] = imageList.get(i).getNAME();
//			Log.i(TAG, "���ϸ� : "+file_name[i]);
			
			Bitmap bitmap = BitmapFactory.decodeFile(file_name[i]);	//�̹��� ��������
//			Log.i(TAG, i+". bitmap : "+bitmap.toString());
			iv.setImageBitmap(bitmap);
			if(i > 1){
				iv.setPadding(0, 0, 50, 0);	
				iv.setScaleType(ImageView.ScaleType.CENTER);
				LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) iv.getLayoutParams();
				lp.setMargins(0, 0, 20, 0);
			}
		
//			iView[0].setImageBitmap(bitmap);
//			iView[i].setImageBitmap(bitmap);
//			iView[i].setImageURI(Uri.parse(dto.getNAME()));
		
//			image_layout.addView(iView[i], new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//			mImageView.setImageBitmap(bitmap);	//�̹����信 �Ѹ���
//			mImageView.setScaleType(ImageView.ScaleType.FIT_XY);	//scale ���߱�
			image_layout.addView(iv);
			
		}//for
	*/
	/*	Intent intentGallery = new Intent();
		intentGallery.setAction(Intent.ACTION_GET_CONTENT);
		intentGallery.setType("image/*");
		startActivityForResult(intentGallery, TAKE_GALLERY);*/
		
	
		
	}
	
	protected void onResume() {
		super.onResume();
		Log.i(TAG, "onResume");
		
		BoardDTO board = new BoardDTO();
		Intent intent = getIntent();
		no = Integer.parseInt(intent.getStringExtra("no"));		//�Խñ� ��ȣ
		Log.i(TAG, "BOARD_NO : "+no);
		
		boardDB = BoardHandler.open(this);
		board = boardDB.getDetail(no);
		
		imageDB = ImageHandler.open(this);
		imageList = new ArrayList<ImageDTO>();
		imageList = imageDB.getList(no);
		
		adapter = new ImageListAdapter(this, imageList);
		grid_image.setAdapter(adapter);
		
		tv_no.setText(board.getNO()+"");
		tv_id.setText(board.getID());
		et_title.setText(board.getTITLE());
		et_content.setText(board.getCONTENT());
		
	};
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_delete:
			boardDB = BoardHandler.open(this);
			imageDB = ImageHandler.open(this);
			
			AlertDialog.Builder ad = new AlertDialog.Builder(this);
			ad.setTitle("Delete");
			ad.setMessage("delete "+no+"??");
			ad.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					int succ = boardDB.delete(no);
					if(succ > 0){	//�Խñ� ����
						int res = imageDB.delete(no);
						if(res>0){	//�Խñۿ� �޸� ���� ����
							Toast.makeText(getApplicationContext(), "delete success", Toast.LENGTH_SHORT).show();
							
							goList();
						}
						else{
							Toast.makeText(getApplicationContext(), "delete image data failed...", Toast.LENGTH_SHORT).show();
						}
					}
					else{
						Toast.makeText(getApplicationContext(), "delete board data failed....", Toast.LENGTH_SHORT).show();
						onResume();
					}
				}
			}).setNegativeButton("No", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					onResume();
				}
			});
			AlertDialog dialog = ad.create();
			dialog.show();
		
			break;
		case R.id.btn_update:
			boardDB = BoardHandler.open(this);
			Log.i(TAG, no+"");
			BoardDTO board = new BoardDTO();
			board.setNO(Integer.parseInt(tv_no.getText().toString()));
			board.setTITLE(et_title.getText().toString());
			board.setCONTENT(et_content.getText().toString());
			
			succ = boardDB.update(board);
			Log.i(TAG, succ+"");
			if(succ > 0){
				Intent ListIntent = new Intent(this, BoardListActivity.class);
				startActivity(ListIntent);
				Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_SHORT).show();
				finish();
			}
			else{
				Toast.makeText(getApplicationContext(), "update failed...", Toast.LENGTH_SHORT).show();
				return;
			}
			break;
			
		case R.id.btn_delete_picture :
			if(adapter == null || adapter.cnt <=0){
//				Log.i(TAG, adapter.cnt+"");
				Toast.makeText(this, "선택된 사진이 없습니다."+adapter.cnt, Toast.LENGTH_SHORT).show();
				return;
			}
			else{
				AlertDialog.Builder ad1 = new AlertDialog.Builder(this);
				ad1.setTitle("Delete");
				ad1.setMessage("삭제하시겠습니까??");
				ad1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						int res = 0;
						for(int i=0; i<adapter.list.size(); i++){
							if(adapter.list.get(i).isChecked()){
								Log.i(TAG, adapter.list.get(i).NO+"삭제??");	//체크된 이미지 NO
								res += imageDB.delete(adapter.list.get(i).NO);
							}
						}
						if(res>0){	
							Toast.makeText(getApplicationContext(), "delete success", Toast.LENGTH_SHORT).show();
//							goList();
							onResume();
							tv_selected_images.setVisibility(View.GONE);
							tv_selected_count.setVisibility(View.GONE);
							btn_delete_picture.setVisibility(View.GONE);
						}
						else{
							Toast.makeText(getApplicationContext(), "delete image data failed...", Toast.LENGTH_SHORT).show();
						}
					}
				}).setNegativeButton("No", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				AlertDialog dialog1 = ad1.create();
				dialog1.show();
				
				
			}
			
			break;
		case R.id.iv_image :
			ImageView picture = (ImageView)v.findViewById(R.id.iv_image);	//row의 iv
			adapter.myChecked((Integer)picture.getTag());		//몇 번째의 item의 image 인지 return
			adapter.notifyDataSetChanged();						//data 변경시 호출.. adapter에 data 변경 사실알려줘서 update 함
			Log.i(TAG, "checked image.... "+picture.getTag());
			break;
		case R.id.checkBox :
			
			break;
		default:
			break;
		}
	}
	
	
//	클릭시 크게 보기
	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		// TODO Auto-generated method stub
		CheckBox check = (CheckBox)v.findViewById(R.id.checkBox);
		Log.i(TAG, "checkBox???"+check.getVisibility());
		
		
		Log.i(TAG, position+" 번째 사진");
		
		Intent inten1t = getIntent();
		Intent intent = new Intent(this, FullImageActivity.class);
		no = Integer.parseInt(inten1t.getStringExtra("no"));	//게시글 번호
		
		Log.i(TAG, "BOARD_NO : "+no );
		intent.putExtra("IMAGE_NO", imageList.get(position).NO);
		intent.putExtra("IMAGE_PATH", imageList.get(position).NAME);
		intent.putExtra("BOARD_NO", no);
		
		Log.i(TAG, "selected image_path : "+ imageList.get(position).NAME);
		startActivity(intent);
	}
	
	
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		boolean b = false;
		adapter = new ImageListAdapter(this, imageList, position, this);
		grid_image.setAdapter(adapter);
		
		tv_selected_images.setText("1");
		tv_selected_count.setText( " 개 선택");
		tv_selected_images.setVisibility(View.VISIBLE);
		tv_selected_count.setVisibility(View.VISIBLE);
		btn_delete_picture.setVisibility(View.VISIBLE);
		
		adapter.setOnTestClickListener(onTestClickListener);
//		RelativeLayout item_view = (RelativeLayout)view; 
		
	/*	checkBox = (CheckBox)parent.findViewById(R.id.checkBox);
		RelativeLayout layout = (RelativeLayout)findViewById(R.id.RelativeLayout1);
		int count_child = layout.getChildCount();
		Log.i(TAG, "children 수 : "+count_child);
		checkBox = (CheckBox) parent.findViewById(R.id.checkBox);
		checkBox = (CheckBox)layout.getChildAt(1);
		checkBox = (CheckBox)grid_image.findViewById(R.id.checkBox);
	*/
	
		
		
		Log.i(TAG, "long clicked # : "+position);
//		checkBox.setVisibility(View.VISIBLE);
		
		return b;
	}

	private onTestClick onTestClickListener = new onTestClick() {
		
		@Override
		public void onClick() {
			tv_selected_images.setText(adapter.cnt+"");
			Log.i(TAG, "PARENT : onTestClick");
		}
	};
	
	@Override
	public boolean onLongClick(View v) {
		Log.i(TAG, "Gridview is longclicked");
		return true;
	}

	public void goList(){
		Intent intent = new Intent(this, BoardListActivity.class);
		startActivity(intent);
		finish();
	}
	
	
	@Override
	public void onBackPressed() {
//		super.onBackPressed();
		goList();
	}
}
